<template>
  <!-- 单条折线图与多条柱形图 -->
  <div>
    <div ref="fullScreenBox" :id="chartId" class="chart"></div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import Ecolors from "@/utils/chartColors";
import { resize, spaceTxt } from "@/utils/utils";
import * as echarts from "echarts";

export default {
  mixins: [resize],
  props: {
    chartId: {
      type: String,
    },
    chartData: {
      type: Array,
    },
  },
  data() {
    return {
      chart: null,
      graphType: "bar",
      colors: [],
      xData: [],
      yData: [],
      legendData: [],
      colorbar: null,
    };
  },
  computed: {
    ...mapState(["curChartConfig"]),
  },
  watch: {
    curChartConfig: {
      deep: true,
      handler: function () {
        this.getCurChartConfig();
      },
    },
    chartData() {
      if (Object.keys(this.chartData).length <= 0) {
        if (this.chart) this.chart.clear();
      } else {
        this.getCurChartConfig();
      }
    },
  },
  mounted() {
    this.chart = this.$echarts.init(document.getElementById(this.chartId));
    this.$emit("domRef", document.getElementById(this.chartId))
    this.getCurChartConfig();
  },
  methods: {
    getCurChartConfig() {
      if (Object.keys(this.curChartConfig).length > 0) {
        let colors = [];
        this.curChartConfig.colors.forEach((v) => {
          colors.push(v.color);
        });
        this.colors = [...colors, ...Ecolors.color];
        let graphType = this.curChartConfig.graphType;
        if (this.curChartConfig.graphType === "bar1") {
          graphType = "bar";
        } else if (this.curChartConfig.graphType === "bar2") {
          graphType = "bar";
        } else if (this.curChartConfig.graphType === "pie1") {
          graphType = "pie";
        }
        this.graphType = graphType;
      }
      if (Object.keys(this.chartData).length > 0) {
        this.init();
      }
      this.colorbar = new echarts.graphic.LinearGradient(
        0,
        0,
        0,
        1,
        [
          {
            offset: 0,
            color: "rgba(0,122,255,1)", // 100% 处的颜色
          },
          {
            offset: 1,
            color: "rgba(255,255,255,1)", // 0% 处的颜色
          },
        ],
        false
      );
    },
    hexToRgba(hex, opacity) {
      let rgbaColor = "";
      let reg = /^#[\da-f]{6}$/i;
      if (reg.test(hex)) {
        rgbaColor = `rgba(${parseInt("0x" + hex.slice(1, 3))},${parseInt(
          "0x" + hex.slice(3, 5)
        )},${parseInt("0x" + hex.slice(5, 7))},${opacity})`;
      }
      return rgbaColor;
    },
    getSeriesData() {
      let seriesData = [];
      let newChartData = JSON.parse(JSON.stringify(this.chartData));
      // x轴数据
      this.xData = newChartData[0]["xArr"];
      // y轴数据
      this.yData = newChartData[0]["yArr"];

      let data = [];
      this.xData &&
        this.xData.forEach((v, i) => {
          let obj = {
            name: v,
            value: this.yData[i],
            label: {
              show: this.curChartConfig["showLabel"],
              position: "top",
              color: "#6b6c7e",
              fontSize: this.curChartConfig["fontSize"] || 12,
              // formatter(a) {
              //   // console.log("a", a.data);
              //   return `${a.data.name}：${a.data.value}`;
              // },
            },
            itemStyle: {
              normal: {
                color:
                  this.curChartConfig.graphType === "pie1"
                    ? this.colors[i - 1]
                    : "#0090FF",
                // barBorderRadius: [20, 20, 20, 20],
                // shadowColor: "rgba(0,160,221,1)",
                shadowBlur: 0,
              },
            },
            custom_selected: false, // 用来判断是否是选中状态
            custom_color: this.colors[i], // 记录默认颜色
          };
          if (this.graphType == "pie") {
            obj.label["formatter"] = (a) => {
              console.log("a", a);
              return `${a.data.name}：${a.data.value}(${a.percent}%)`;
            };
          }
          data.push(obj);
        });

      let obj = {
        type: this.graphType,
        // name: 'a',
        symbol: "circle",
        symbolSize: "8",
        connectNulls: true,
        // smooth: true,
        scale: true,
        lineStyle: {
          normal: {
            color: "#0090FF",
          },
        },
        areaStyle: {
          normal: {
            color: new echarts.graphic.LinearGradient(
              0,
              0,
              0,
              1,
              [
                {
                  offset: 0,
                  color: this.hexToRgba("#0090FF", 0.6),
                },
                {
                  offset: 1,
                  color: this.hexToRgba("#0090FF", 0.1),
                },
              ],
              false
            ),
            shadowColor: this.hexToRgba("#0090FF", 0.1),
            shadowBlur: 10,
          },
        },
      };
      if (this.graphType === "pie1") {
        obj = {
          ...obj,
          radius: ["55%", "75%"],
          center: ["50%", "45%"],
          label: {
            show: this.curChartConfig["showLabel"],
            fontSize: this.curChartConfig["fontSize"] || 12,
          },
          labelLine: {
            show: true,
          },
          minShowLabelAngle: 4,
          data: data,
        };
      } else {
        obj = {
          ...obj,
          barMaxWidth: 30,
          barMinHeight: 10,
          barWidth: 30,
          data: data,
        };
      }
      seriesData.push(obj);
      return seriesData;
    },
    init() {
      let seriesData = this.getSeriesData();
      // 图例
      let legend = {
        type: "plain",
        show: this.curChartConfig["showLegend"],
        left: "center",
        // right: "4%",
        // top: "5%",
        icon: "circle",
        textStyle: {
          color: "#6b6c7e",
        },
        // data: seriesData[0].data
        // data: this.xData
      };
      // 轴线
      let xAxisLine = {
        lineStyle: {
          color:
            this.curChartConfig["axisLine"] &&
            this.curChartConfig["axisLine"].checked
              ? this.curChartConfig["axisLine"].color
              : "#777",
          width: 1,
          type:
            this.curChartConfig["axisLine"] &&
            this.curChartConfig["axisLine"].checked
              ? this.curChartConfig["axisLine"].type
              : "solid",
        },
      };
      // x轴分隔线
      let xSplitLine = {
        show:
          this.curChartConfig["xGridLine"] &&
          this.curChartConfig["xGridLine"].checked,
        lineStyle: {
          color:
            (this.curChartConfig["xGridLine"] &&
              this.curChartConfig["xGridLine"].color) ||
            "#f0f1f3",
          type:
            this.curChartConfig["xGridLine"] &&
            this.curChartConfig["xGridLine"].type,
        },
      };
      // y轴分隔线
      let ySplitLine = {
        show:
          this.curChartConfig["yGridLine"] &&
          this.curChartConfig["yGridLine"].checked,
        lineStyle: {
          color:
            (this.curChartConfig["yGridLine"] &&
              this.curChartConfig["yGridLine"].color) ||
            "#f0f1f3",
          type: this.curChartConfig["yGridLine"].type,
        },
      };
      // 背景色
      let backgroundColor =
        this.curChartConfig["showBgColor"] &&
        this.curChartConfig["showBgColor"].checked
          ? this.curChartConfig["showBgColor"].color
          : "#fff";

      let option = {
        tooltip: {
          confine: true,
          show: true,
          trigger: this.graphType === "pie" ? "item" : "axis",
          backgroundColor: "#fff",
          extraCssText: "box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);",
          borderRadius: 0,
          padding: 5,
          textStyle: {
            color: "#000",
          },
        },
        // 图例
        legend,
        // 背景色
        backgroundColor,
        xAxis: {
          type: "category",
          boundaryGap: true,
          // 轴线
          // axisLine: xAxisLine,
          axisLabel: {
            rotate: 40,
            interval: 0,
            margin: 10,
            textStyle: {
              color: "#666666",
            },
            formatter: (label) => {
              return spaceTxt(label, 20);
            },
          },
          // 分隔线
          splitLine: xSplitLine,
          data: this.xData,
        },
        yAxis: {
          type: "value",
          minInterval: 1,
          axisTick: {
            show: false,
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: "#f0f1f3",
              width: 2,
            },
          },
          axisLabel: {
            textStyle: {
              color: "#666666",
            },
          },
          // 分隔线
          splitLine: ySplitLine,
        },
        series: seriesData,
      };
      if (this.graphType !== "pie") {
        option.tooltip.trigger = "axis";
        option.grid = {
          top: "50px",
          right: "20px",
          left: "20px",
          bottom: "20px",
          containLabel: true,
        };
      } else {
        let formatter = (params) => {
          let str = `${params.marker}${params.data.name}：${params.data.value}`;
          return str;
        };
        option.tooltip.trigger = "item";
        option.tooltip.formatter = formatter;
        option.xAxis.show = false;
        option.yAxis.show = false;
      }
      this.chart.clear();
      this.chart.setOption(option);
      this.$emit("chartDom", this.chart);

      // 点击进行对比分析，只有专利分析3.1和4.1图有点击对比分析逻辑
      if (this.chartId == "chart301000" || this.chartId == "chart401000") {
        this.chart.off("click");
        this.chart.on("click", (params) => {
          if (this.curChartConfig.graphType === "pie1") {
            return;
          } else {
            let dataIndex = params.dataIndex;
            let op = this.chart.getOption();
            op.series[0].data.forEach((v, i) => {
              if (i == dataIndex) {
                if (v.custom_selected === true) {
                  // v.itemStyle.color = v.custom_color;
                  v.itemStyle.color = "#0090FF"
                } else {
                  v.itemStyle.color = "red";
                }
                v.custom_selected = !v.custom_selected;
              }
            });
            this.getContrastiveData(op);
            this.chart.setOption(op);
          }
        });
      }
      

      // 后台报告下载
      this.chart.on("finished", () => {
        let tempId = this.$route.query.tempId;
        if (tempId) {
          this.getEchartImg(this.chart.getDataURL());
        }
      });
    },
    getEchartImg(base) {
      let dom = document.getElementById("echartImgFinished");
      if (dom) {
        document.getElementById("app").removeChild(dom);
      }
      window.echartImg = base;
      let _echartImg = document.createElement("div");
      _echartImg.setAttribute("id", "echartImgFinished");
      document.getElementById("app").appendChild(_echartImg);
    },
    // 保存对比分析数据
    getContrastiveData(option) {
      let arr = [];
      option.series[0].data.forEach((v, i) => {
        if (v.custom_selected === true) {
          arr.push(v);
        }
      });
      this.$emit("contrastiveData", arr);
    },
  },

  destroyed() {
    this.chart.dispose();
    this.chart = null;
  },
};
</script>

<style lang="scss" scoped>
// .chart {
//   background-color: #fff;
// }
</style>
